package com.drinks.yiniang.ui.fragment.shopping;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.shop.ShoppingCartAdapter;
import com.drinks.yiniang.common.recycler.decoration.ShoppingCartItemDecoration;
import com.drinks.yiniang.common.listener.OnCartHandleClickListener;
import com.drinks.yiniang.common.listener.OnCounterClickListener;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.event.ShopCartChangeEvent;
import com.drinks.yiniang.entity.event.ShopCartEvent;
import com.drinks.yiniang.entity.shop.ShoppingCartJson;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.activity.user.order.OrderConfirmActivity;
import com.drinks.yiniang.ui.widget.dialog.NumpadDialog;
import com.drinks.yiniang.ui.widget.layout.CartBottomLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.listener.OnNumPadInputListener;
import com.hansen.library.listener.OnSureCancelListener;
import com.hansen.library.ui.fragment.BaseFragment;
import com.hansen.library.ui.widget.dialog.Material2Dialog;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.ArithmeticUtil;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static com.drinks.yiniang.entity.shop.ShoppingCartJson.ITEM_TYPE_CART_GOODS;
import static com.drinks.yiniang.entity.shop.ShoppingCartJson.ITEM_TYPE_CART_RECOMMEND;
import static com.drinks.yiniang.entity.shop.ShoppingCartJson.ITEM_TYPE_CART_RECOMMEND_TITLE;

/**
 * 购物车页面
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class ShoppingCartPageFragment extends BaseFragment implements OnNavgationBarClickListener,
        SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener, OnCounterClickListener, ShoppingCartAdapter.OnListCountChangeListener,
        OnCartHandleClickListener, OnSureCancelListener, OnNumPadInputListener {

    //nav bar
    private NavigationBarLayout nav_bar_shopping_cart;
    private MSwipeRefreshLayout refresh_shopping_cart;
    //列表
    private BaseRecyclerView rcv_shopping_cart;
    private CartBottomLayout ll_cart_bottom;
    //header view
    private TextView tv_shopping_cart_empty;

    private ShoppingCartAdapter mShoppingCartAdapter;

    //重新刷新购物车数据
    private boolean isNeedRefresh;

    public ShoppingCartPageFragment() {
        // Required empty public constructor
    }

    public static ShoppingCartPageFragment newInstance() {
        return new ShoppingCartPageFragment();
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_shopping_cart_page;
    }

    @Override
    protected void initView(View mView) {
        nav_bar_shopping_cart = mView.findViewById(R.id.nav_bar_shopping_cart);

        refresh_shopping_cart = mView.findViewById(R.id.refresh_shopping_cart);

        rcv_shopping_cart = mView.findViewById(R.id.rcv_shopping_cart);

        ll_cart_bottom = mView.findViewById(R.id.ll_cart_bottom);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        initAdapter();
        getCartList();
    }

    private void initAdapter() {
        mShoppingCartAdapter = new ShoppingCartAdapter(mContext, new ArrayList<ShoppingCartJson.ShoppingCartList>());
        mShoppingCartAdapter.addHeaderView(getHeaderView());
        mShoppingCartAdapter.setHeaderAndEmpty(true);
        mShoppingCartAdapter.setCenterEmpty(getLayoutInflater(), rcv_shopping_cart);
        mShoppingCartAdapter.bindToRecyclerView(rcv_shopping_cart);

        rcv_shopping_cart.addItemDecoration(ShoppingCartItemDecoration.getItemDPDecoration(10));
        rcv_shopping_cart.setLayoutManager(RecyclerUtils.getShoppingCartGridLayout(mContext, mShoppingCartAdapter.getData()));
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_shopping_cart_empty, (ViewGroup) rcv_shopping_cart.getParent(), false);

        tv_shopping_cart_empty = mHeaderView.findViewById(R.id.tv_shopping_cart_empty);

        return mHeaderView;
    }

    @Override
    protected void listener() {
        nav_bar_shopping_cart.setOnNavgationBarClickListener(this);
        ll_cart_bottom.setOnCartHandleClickListener(this);
        refresh_shopping_cart.setOnRefreshListener(this);
        mShoppingCartAdapter.setOnItemClickListener(this);
        mShoppingCartAdapter.setOnItemChildClickListener(this);
        mShoppingCartAdapter.setOnCounterClickListener(this);
        mShoppingCartAdapter.setOnListCountChangeListener(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void widgetClick(View v) {

    }

    @Override
    public void onBackClick(View v) {

    }

    @Override
    public void onEditClick(View v) {
        //删除
        showDeleteSureDialog();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isNeedRefresh) {
            getCartList();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isNeedRefresh && !isHidden()) {
            getCartList();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShopCartEvent event) {
        isNeedRefresh = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShopCartChangeEvent event) {
        isNeedRefresh = true;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

        if (data == null) {
            return;
        }

        Intent mIntent;

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_CART_GOODS://购物车里的商品
                setChecked(data, position);
                break;
            case ITEM_TYPE_CART_RECOMMEND://推荐商品列表
                mIntent = new Intent(mContext, GoodsDetailsActivity.class);
                mIntent.putExtra(Constants.KeyGoodsId, data.getId());
                startActivity(mIntent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

        if (data == null) {
            return;
        }

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_CART_RECOMMEND:
                if(view.getId() == R.id.iv_home_goods_add_cart) addToCart(data.getId());
                break;
                default:
                    break;
        }
    }

    @Override
    public void onCounterClick(int position) {
        ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

        if (data != null && ITEM_TYPE_CART_GOODS == data.getItemType()) {
            NumpadDialog dialog = NumpadDialog.newInstance(position, data.getNum());

            dialog.show(getChildFragmentManager(), Constants.TAG_ADD_TO_CART_NUM);
        }
    }

    @Override
    public void onNumPadInputSuccess(int position, String params, String value, boolean isInputChange) {
        if(StringUtils.isEmpty(value)) {
            return;
        }

        ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

        if (data != null && ITEM_TYPE_CART_GOODS == data.getItemType()) {
            if(isInputChange) {//输入框实时输入
                if(value != null && !value.equals(data.getNum())) {
                    data.setNum(value);
                    mShoppingCartAdapter.setData(position, data);
                }
            } else {//确认输入
                if(value != null && !value.equals(params)) {
                    modifyNum(position, data.getId(), data.getNum(), params);
                }
            }
        }
    }

    @Override
    public void onListCountChange(int position, int count) {
        ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

        if (data != null && ITEM_TYPE_CART_GOODS == data.getItemType()) {
            String oldNum = data.getNum();

            data.setNum(String.valueOf(count));
            mShoppingCartAdapter.setData(position, data);
            modifyNum(position, data.getId(), data.getNum(), oldNum);
        }
    }

    @Override
    public void onCheckAllClick(View v, boolean isCheckAll) {//全选
        //全选或取消全选
        if (checkCartListIsEmpty()) {
            return;
        }

        String totalMoney = "0.0";

        ShoppingCartJson.ShoppingCartList dataObj;

        for (int i = 0; i < mShoppingCartAdapter.getData().size(); i++) {
            dataObj = mShoppingCartAdapter.getData().get(i);

            if (ITEM_TYPE_CART_GOODS == dataObj.getItemType()) {
                dataObj.setChecked(isCheckAll);
                if (isCheckAll) {
                    totalMoney = ArithmeticUtil.addAmount(totalMoney, ArithmeticUtil.mulScaleAmount(dataObj.getItem_price(), dataObj.getNum()));
                }
            }
        }

        mShoppingCartAdapter.notifyDataSetChanged();

        ll_cart_bottom.setCheckAll(isCheckAll);
        ll_cart_bottom.setSettleAccountButtonEnable(isCheckAll);
        ll_cart_bottom.setTotalText(totalMoney, false);
    }

    @Override
    public void onToSettleAccountClick(View v) {//去结算
        String ids = formatCardId();

        if (StringUtils.isEmpty(ids)) {
            return;
        }

        Intent intent = new Intent(mContext, OrderConfirmActivity.class);
        intent.putExtra(Constants.KeyId, ids);
        startActivity(intent);
    }

    @Override
    public void onSure(int type, String value) {
        deleteCartGoods(value);
    }

    @Override
    public void onCancel(int type) {

    }

    @Override
    public void onRefresh() {
        getCartList();
    }

    private void showDeleteSureDialog() {
        String ids = formatCardId();

        if (StringUtils.isEmpty(ids)) {
            return;
        }

        int chooseNum = ids.split(",").length;

        Material2Dialog dialog = Material2Dialog.newInstance(String.format(getString(R.string.text_sure_delete_cart_goods), chooseNum), ids);

        dialog.show(getChildFragmentManager(), Constants.TAG_TIPS_DIALOG);
    }

    //删除商品
    private void deleteCartGoods(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return;
        }

        showLoadingDialog();

        ShoppingCartApiIO.getInstance().deleteGoodsFromShopCart(ids, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if (mShoppingCartAdapter == null) {
                    return;
                }

                for (int i = mShoppingCartAdapter.getData().size() - 1; i >= 0; i--) {
                    if (mShoppingCartAdapter.getItem(i).isChecked()) {
                        mShoppingCartAdapter.remove(i);
                    }
                }

                clearAllCheck();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //修改购物车商品数量
    private void modifyNum(final int position, String cardId, String newNum, final String oldNum) {
        if(StringUtils.isEmpty(cardId)) {
            ToastUtils.showShort(R.string.text_the_goods_does_not_exist);
            return;
        }

        showLoadingDialog();

        ShoppingCartApiIO.getInstance().modifyGoodsNumFromShopCart(cardId, newNum, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

                if(data == null) {
                    return;
                }

                if(data.isChecked()) {
                    calculateCheckTotal();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                //修改失败，数量变为原来的数量
                ShoppingCartJson.ShoppingCartList data = mShoppingCartAdapter.getItem(position);

                if (data != null) {
                    data.setNum(oldNum);
                    mShoppingCartAdapter.setData(position, data);
                }
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取购物车列表
    private void getCartList() {
        if (!refresh_shopping_cart.isRefreshing()) {
            showLoadingDialog();
        }

        ShoppingCartApiIO.getInstance().getShopCartList(new APIRequestCallback<ShoppingCartJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(ShoppingCartJson res) {
                if (mShoppingCartAdapter == null) {
                    return;
                }

                mShoppingCartAdapter.getData().clear();
                mShoppingCartAdapter.addData(res.getData());
                mShoppingCartAdapter.loadMoreEnd();

                clearAllCheck();

                getRecommendGoodsList();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mShoppingCartAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                isNeedRefresh = false;
                refresh_shopping_cart.setRefreshing(false);
                dismissDialog();
            }
        });
    }

    //获取购物车里的推荐商品
    private void getRecommendGoodsList() {
        ShoppingCartJson.ShoppingCartList data = new ShoppingCartJson.ShoppingCartList();
        data.setItemType(ITEM_TYPE_CART_RECOMMEND_TITLE);

        mShoppingCartAdapter.addData(data);

        ShoppingCartApiIO.getInstance().getShopCartRecommendGoodsList(new APIRequestCallback<ShoppingCartJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(ShoppingCartJson res) {

                for (int i = 0; i < res.getData().size(); i++) {
                    res.getData().get(i).setItemType(ITEM_TYPE_CART_RECOMMEND);
                }

                mShoppingCartAdapter.addData(res.getData());
                mShoppingCartAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    //设置选中
    private void setChecked(ShoppingCartJson.ShoppingCartList data, int pos) {
        if (data == null) {
            return;
        }

        data.setChecked(!data.isChecked());

        mShoppingCartAdapter.setData(pos, data);

        calculateCheckTotal();
    }

    private void calculateCheckTotal() {
        boolean isCheckAll = true;
        boolean hasChooseGoods = false;

        String totalMoney = "0.0";
        ShoppingCartJson.ShoppingCartList dataObj;

        for (int i = 0; i < mShoppingCartAdapter.getData().size(); i++) {
            dataObj = mShoppingCartAdapter.getItem(i);

            if (ITEM_TYPE_CART_GOODS == dataObj.getItemType()) {
                if (!dataObj.isChecked()) {
                    isCheckAll = false;
                } else {
                    hasChooseGoods = true;
                    totalMoney = ArithmeticUtil.addAmount(totalMoney, ArithmeticUtil.mulScaleAmount(dataObj.getItem_price(), dataObj.getNum()));
                }
            }
        }

        if (isCheckAll) {
            ll_cart_bottom.setCheckAll(true);
        } else {
            ll_cart_bottom.setCheckAll(false);
        }

        ll_cart_bottom.setTotalText(totalMoney, false);
        ll_cart_bottom.setSettleAccountButtonEnable(hasChooseGoods);
    }

    private void clearAllCheck() {
        ll_cart_bottom.setCheckAll(false);
        ll_cart_bottom.setTotalText("0.00", false);
        ll_cart_bottom.setSettleAccountButtonEnable(false);

        tv_shopping_cart_empty.setVisibility(checkCartListIsEmpty() ? View.VISIBLE : View.GONE);
    }

    //判断是否为空的购物车
    private boolean checkCartListIsEmpty() {
        if (CommonUtils.isEmptyList(mShoppingCartAdapter.getData())) {
            return true;
        }

        for (int i = 0; i < mShoppingCartAdapter.getData().size(); i++) {
            if (ITEM_TYPE_CART_GOODS == mShoppingCartAdapter.getItem(i).getItemType()) {
               return false;
            }
        }

       return true;
    }

    //获取已选择的商品cartId
    private String formatCardId() {
        if (CommonUtils.isEmptyList(mShoppingCartAdapter.getData())) {
            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();

        List<String> mIds = new ArrayList<>();

        ShoppingCartJson.ShoppingCartList data;

        //遍历问题id集合和答案集合拼接字符串 作为单数请求服务器
        for (int i = 0; i < mShoppingCartAdapter.getData().size(); i++) {
            data = mShoppingCartAdapter.getItem(i);

            if (ITEM_TYPE_CART_GOODS == data.getItemType() && data.isChecked()) {
                mIds.add(data.getId());
            }
        }

        for (int i = 0; i < mIds.size(); i++) {
            stringBuilder.append(mIds.get(i));

            if (i < mIds.size() - 1) {
                stringBuilder.append(",");
            }
        }

        return stringBuilder.toString();
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
                isNeedRefresh = false;
                getCartList();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onDestroy() {
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        isNeedRefresh = false;
        super.onDestroy();
    }
}
